package com.liangwj.springbootquickstart.aop;

import com.liangwj.springbootquickstart.MultiDataSource.DynamicDataSource;
import com.liangwj.springbootquickstart.MultiDataSource.DynamicDataSourceHolder;
import com.liangwj.springbootquickstart.annotation.DataSource;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

/**
 * TODO: 搭配@DataSource而写的AOP
 * @author Liangwenjun
 * @date 2018-12-12
 * @version 1.0
 */
@Component
@Aspect
public class DataSourceAspect {

    @Pointcut("execution(public * com.liangwj.springbootquickstart.services.*.*(..))")
    public void aspect() {

    }

    @Before(value = "aspect()")
    public void before(JoinPoint jp) throws NoSuchMethodException {
        Class<?> _class = jp.getTarget().getClass();
        DataSource anno = _class.getAnnotation(DataSource.class);
        if (anno != null) {
//            DynamicDataSource.key.set(anno.value());
            DynamicDataSourceHolder.setThreadDatasource(anno.value());
            System.out.println("DataSource.value():" + anno.value());
        } else {
            String key = (String) DataSource.class.getMethod("value").getDefaultValue();
            DynamicDataSourceHolder.setThreadDatasource(key);
        }

    }
}
